﻿namespace Growatt.ShinebusServiceUploadPack.Service.OSS
{
    using System;
    using System.Net.Http;
    using System.Text;
    using System.Threading.Tasks;
    using Growatt.ShinebusServiceUploadPack.Controllers;
    using Growatt.ShinebusServiceUploadPack.Service.OSS.Model;

    public class GetAllProductTypes
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public GetAllProductTypes(IHttpClientFactory httpClientFactory)
        {
            this._httpClientFactory = httpClientFactory;
        }
        public  async Task<GetAllProductTypesResponse> GetAllProductTypesAsync(ILogger<UpdatePackController> logger, string Server = "20.6.1.140:8081")
        {
            // 创建HttpClient实例
            using (HttpClient client = _httpClientFactory.CreateClient())
            {
                // 创建FormUrlEncodedContent实例
                var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("op", "getDevieceSoftType"), new KeyValuePair<string, string>("lang", "cn") });

                // 发送POST请求
                HttpResponseMessage response = await client.PostAsync($"http://{Server}/pubData.do", content);

                // 检查响应状态码
                if (response.IsSuccessStatusCode)
                {
                    // 读取响应内容
                    string responseBody = await response.Content.ReadAsStringAsync();
                    logger.LogInformation("获取所有产品类型成功: " );

                    // 将响应内容反序列化为实体对象
                    GetAllProductTypesResponse responseObj = Newtonsoft.Json.JsonConvert.DeserializeObject<GetAllProductTypesResponse>(responseBody);

                    return responseObj;
                }
                else
                {
                    logger.LogInformation("获取所有设备类型和设备机型失败: " + response.StatusCode);
                }
            }

            return null;
        }
    }
}
